package com.wynn.security;
import com.alibaba.fastjson.JSONObject;
import com.wynn.config.JwtUtils;
import com.wynn.pojo.Result;
import com.wynn.pojo.User;
import com.wynn.serviceFeign.UserClient;
import com.wynn.utils.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private JwtUtils jwtUtils;
	@Autowired
	private UserClient userClient;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=UTF-8");
		ServletOutputStream outputStream = response.getOutputStream();
		// 生成jwt，并放置到请求头中
		String jwt = jwtUtils.generateToken(authentication.getName());
		response.setHeader(jwtUtils.getHeader(), jwt);

		String remoteAddr = request.getRemoteAddr();
		String forwarded = request.getHeader("X-Forwarded-For");
		String realIp = request.getHeader("X-Real-IP");
		String visitorIp = IpUtils.getVisitorIp(remoteAddr, forwarded, realIp);
		Result result = userClient.findByUser(authentication.getName(), visitorIp);


		result.setCode("200");
		result.setMessage("登陆成功");
		request.getSession().setAttribute("user", result.getData());

		outputStream.write(JSONObject.toJSONString(result).getBytes("UTF-8"));

		outputStream.flush();
		outputStream.close();
	}

//	public Result loginIndex( HttpServletRequest request){
//		// 获取访问ip地址
//		String remoteAddr = request.getRemoteAddr();
//		String forwarded = request.getHeader("X-Forwarded-For");
//		String realIp = request.getHeader("X-Real-IP");
//		String visitorIp = IpUtils.getVisitorIp(remoteAddr, forwarded, realIp);
//
//		Result result = userClient.findByUser(user,visitorIp);
//		request.getSession().setAttribute("user", result.getData());
//
//		return result;
//	}

}
